package com.cloudansys.core.util;

import com.cloudansys.config.DefaultConfig;
import com.cloudansys.hawkeye.modules.settings.model.vo.DataWarn;
import lombok.extern.slf4j.Slf4j;

import java.sql.*;
import java.util.List;

@Slf4j
public class MysqlUtil {

//    public static void main(String[] args) {
//        System.out.println(selectTargetCount());
//    }

    /**
     * 批量存储告警信息
     */
    public static void save(List<DataWarn> dataWarns) {
        Connection connection = null;
        PreparedStatement ps = null;
        try {
            //设置手动提交
            connection = DefaultConfig.getMysqlConnection();
            connection.setAutoCommit(false);
            //预编译sql对象,只编译一回
            ps = connection.prepareStatement("INSERT INTO data_warn (target_id, target_type_id, data_json, " +
                    "threshold_json, time_o, quota_id, level, message) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
            for (DataWarn dataWarn : dataWarns) {
                ps.setInt(1, dataWarn.getTargetId());
                ps.setInt(2, dataWarn.getTargetTypeId());
                ps.setString(3, dataWarn.getDataJson());
                ps.setString(4, dataWarn.getThresholdJson());
                ps.setTimestamp(5, new Timestamp(dataWarn.getTimeO().getTime()));
                ps.setInt(6, dataWarn.getQuotaId());
                ps.setInt(7, dataWarn.getLevel());
                ps.setString(8, dataWarn.getMessage());

                //添加到批次
                ps.addBatch();
            }
            //提交批处理
            ps.executeBatch();
            //执行
            connection.commit();
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeAll(ps, null, null, connection);
        }
    }

    /**
     * 释放资源
     */
    private static void closeAll(PreparedStatement ps, Statement stmt, ResultSet rs, Connection conn) {
        if (ps != null) {
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}
